import type { BlockProcessor, PreBlock, Row } from '../types';

const REGEXP = /^[ ]{0,3}#{1,6}[ ]?/;

const isBlockBegin = (row: Row) => REGEXP.test(row.value);

const atxHeadingProcessor: BlockProcessor = {
  isBlockBegin,
  process: (pbs) => {
    const result: PreBlock[] = [];
    for (const block of pbs) {
      if (block.type == 'row') {
        const matched = block.value.match(REGEXP);
        if (matched) {
          const mt = matched[0];
          result.push({
            type: 'heading',
            level: mt.trim().length,
            row: { type: 'row', value: block.value.substring(mt.length) },
          });
          continue;
        }
      }
      result.push(block);
    }
    return result;
  },
};

export default {
  processor: atxHeadingProcessor,
};
